import 'dart:async';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:permission_handler/permission_handler.dart'
    as permission_handler;
import '../../index.dart';

class WorkOrderListPage extends StatefulWidget {
  const WorkOrderListPage({Key? key}) : super(key: key);

  @override
  _WorkOrderListState createState() => _WorkOrderListState();
}

class _WorkOrderListState extends State<WorkOrderListPage> {
  final EasyRefreshController _controller = EasyRefreshController();
  final PageData<Order> _pageData = PageData<Order>();
  LatLng? latLng;
  List<FilterSelectData> selectList = [];

  late StreamSubscription loginSubscription;
  List<OrderCfg>? repairSource;
  List<OrderCfg>? emergencyLevel;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    loginSubscription = eventBus.on<OrderEvent>().listen((event) {
      Debug.info("刷新工单列表");
      _handlerRefresh();
    });
    repairSource = OrderCfgCache().getOrderCfg(2);
    emergencyLevel = OrderCfgCache().getOrderCfg(3);
    //添加经纬度
    PermissionHelper.check([permission_handler.Permission.location],
        onSuccess: () async {
      try {
        // 单次定位
        Location location = await AmapLocation.instance.fetchLocation();
        latLng = location.latLng;
      } on Error catch (e) {
        // Navigator.of(context).pop();
        showToast("定位失败");
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    //取消订阅
    loginSubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> actions = [];
    if (PermissionCache().getPermission("work_order_add") != null) {
      actions.add(IconButton(
          onPressed: () {
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => WorkOrderAddPage()));
          },
          icon: const Icon(Icons.add)));
    }

    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: Scaffold(
          appBar: AppBar(
            title: Text(
              S.of(context).workOrderList,
            ),
            centerTitle: true,
            actions: actions,
          ),
          body: FutureBuilder(
              future: DefaultAssetBundle.of(context)
                  .loadString('load_jsons/work_order_filter.json'),
              builder: (context, snapshot) {
                if (snapshot.connectionState != ConnectionState.done) {
                  return Container();
                }
                List<FilterItemData>? filterItemList = FilterUtils.jsonToFilterList(snapshot.data.toString());
                if(repairSource!=null) {
                  List<FilterItemData> itemList = [];
                  for (OrderCfg orderCfg in repairSource!) {
                    itemList.add(FilterItemData(orderCfg.cfgTypeName,value: orderCfg.id));
                  }
                  FilterUtils.addFilterItemToList(
                      filterItemList!, "repairResource", itemList);
                }
                if(emergencyLevel!=null) {
                  List<FilterItemData> itemList = [];
                  for (OrderCfg orderCfg in emergencyLevel!) {
                    itemList.add(FilterItemData(orderCfg.cfgTypeName,value: orderCfg.id));
                  }
                  FilterUtils.addFilterItemToList(
                      filterItemList!, "orderType", itemList);
                }
                return Column(
                  children: [
                    FilterWidget(
                      initConfig: filterItemList,
                      onInit: (List<FilterSelectData> selectList) {
                        this.selectList = selectList;
                        _handlerRefresh();
                      },
                      onSelect: (List<FilterSelectData> selectList) {
                        //选中回调
                        Debug.info(">>>>>选中回调<<<<<");
                        this.selectList = selectList;
                        _pageData.loadStatus = LoadStatus.loading;
                        _pageData.items.clear();
                        //第一次不显示加载框 其它时候加载
                        _handlerRefresh(showLoad: true);
                        // for (var o in selectList) {
                        //   Debug.info("${o.toJson().toString()}");
                        // }
                      },
                    ),
                    Expanded(child: _buildContent())
                  ],
                ); // 构建主页面
              }),
        ),
      ),
    );
  }

  Widget _buildContent() {
    return EasyRefresh(
      header: LightHeader(),
      footer: LightFooter(),
      controller: _controller,
      onRefresh: () => _handlerRefresh(),
      onLoad: () => _handlerRefresh(refresh: false),
      emptyWidget:
          _pageData.items.isEmpty ? HintWidget(pageData: _pageData) : null,
      child: ListView.separated(
        itemCount: _pageData.items.length,
        itemBuilder: (context, index) {
          return WorkOrderItem(_pageData.items[index]);
        },
        separatorBuilder: (BuildContext context, int index) {
          return const Divider(
            height: 1,
          );
        },
      ),
    );
  }

  Future _handlerRefresh({bool refresh = true, bool showLoad = false}) async {
    if (showLoad) {
      showLoading(context);
    }
    try {
      Map<String, dynamic> queryParameters;
      if (refresh) {
        queryParameters = _pageData.newQueryParameters();
        for (FilterSelectData selectData in selectList) {
          queryParameters.addAll({selectData.code: selectData.valueString()});
        }
        if (queryParameters["descs"] == "distance") {
          //距离排序
          queryParameters.addEntries({
            "longitude": latLng?.longitude,
            "latitude": latLng?.latitude
          }.entries);
        }
      } else {
        queryParameters = _pageData.moreQueryParameters();
      }

      _pageData.loadStatus = LoadStatus.loading;
      ResponseData<RecordData<Order>> responseData = await Api(context)
          .getOrderList(queryParameters: queryParameters, refresh: refresh);
      if (responseData.code == 200) {
        RecordData<Order> recordData = responseData.dataModel!;
        List<Order> orders = recordData.recordModels;
        //如果返回的数据小于指定的条数，则表示没有更多数据，反之则否
        //把请求到的新数据添加到items中
        if (mounted) {
          setState(() {
            _pageData.loadStatus = LoadStatus.loadSuccess;
            _pageData.current = recordData.current as int;
            if (_pageData.current == PageData.initCurrent) {
              //第一页
              _pageData.items.clear();
            }
            _pageData.items.addAll(orders.map((e) => e));
            if (_pageData.items.length == recordData.total as int) {
              //没有更多
              _controller.finishLoad(noMore: true);
            } else {
              _controller.finishLoad(noMore: false);
            }
          });
        }
      } else {
        _pageData.hint = responseData.msg;
        //请求失败
        showToast(responseData.msg);
        setState(() {
          _pageData.loadStatus = LoadStatus.loadFail;
        });
      }
    } on DioError catch (e) {
      //登录失败则提示
      _pageData.hint = e.response?.statusMessage ?? S.of(context).networkError;
      _pageData.code = e.response?.statusCode;
      _pageData.errorType = e.type;
      if (_pageData.items.isNotEmpty) {
        showToast(e.response?.statusMessage ?? S.of(context).networkError);
      }
      setState(() {
        _pageData.loadStatus = LoadStatus.loadFail;
      });
    } on Error catch (e) {
      //登录失败则提示
      _pageData.hint =
          Global.isRelease ? S.of(context).networkError : e.toString();
      if (_pageData.items.isNotEmpty) {
        showToast(Global.isRelease ? S.of(context).networkError : e.toString());
      }
      setState(() {
        _pageData.loadStatus = LoadStatus.loadFail;
      });
    } finally {
      if (showLoad) {
        Navigator.of(context).pop();
      }
    }
  }
}
